package top.rainbowecho.gateway.security.authentication.social.qq.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.io.IOException;
import java.util.Objects;

/**
 * @author rainbow
 * @since 2019/12/15 16:38
 */
@Slf4j
public class QqImpl extends AbstractOAuth2ApiBinding implements Qq {
    public static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";

    public static final String URL_GET_USER_INFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";

    private String appId;

    private String openId;

    public QqImpl(String accessToken, String appId) {
        // 让父类自动将accessToken加到uri路径中
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
        this.appId = appId;

        String url = String.format(URL_GET_OPENID, accessToken);
        String result = Objects.requireNonNull(getRestTemplate().getForObject(url, String.class));
        log.info("获取用户openID请求结果：" + result);
        // 腾讯此接口的返回值属于HTML型json
        this.openId = StringUtils.substringBetween(result, "\"openid\":\"", "\"}");
    }

    @Override
    public QqUserInfo getUserInfo() {
        String url = String.format(URL_GET_USER_INFO, this.appId, this.openId);
        String result = getRestTemplate().getForObject(url, String.class);
        log.info("获取qq用户信息响应结果：" + result);
        QqUserInfo userInfo = null;
        try {
            userInfo = new ObjectMapper().readValue(result, QqUserInfo.class);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        Objects.requireNonNull(userInfo).setOpenId(this.openId);
        return userInfo;
    }
}
